package game.leon.engine.net.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/**
 * User: bianpeng
 * Date: 11-12-28
 */
class GameProtocolEncoder extends ProtocolEncoderAdapter {
    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        GameRawMessage rawMessage = (GameRawMessage) message;
        assert rawMessage != null;
        IoBuffer buffer = IoBuffer.allocate(
                rawMessage.getData().length + GameProtocolDecoder.BUFFER_PREFIX_LENGTH + 2,
                false);
        // 这里是实际数据长度, 8字节的PREFIX长度, 不包含在内
        int dataLen = rawMessage.getData().length + 2;
        buffer.putUnsignedShort(dataLen); // 2 bytes data length
        buffer.putUnsignedShort(0); // 2 bytes checksum
        buffer.putUnsignedShort(0); // 2 bytes flag
        buffer.putUnsignedShort(rawMessage.getMessage()); // 2 bytes message
        buffer.put(rawMessage.getData());
        buffer.flip();
        out.write(buffer);
    }
}
